package com.cmfile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.ResultSet;
import java.util.List;

import com.cm.Cm_Main;
import com.cm.Cm_file;
import com.cm.Cm_object;
import com.cm.Cm_root_object;
import com.cm.Cmfileheader;
import com.cm.Root_sqlfield;
import com.cm.Sqlfield;
import com.util.ConnectionPool;
import com.util.Constant;
import com.util.FTPClientImp;
import com.util.FTPClientInterface;
import com.util.NrmUtil;

public class GenerateCmFileImp {

	private List<Cm_file> cmfileList;
	private String neName = "aaa";
	private String dateTime = "20151203-1815";
	private BufferedWriter buf;
	private StringBuffer strBuf;

	public void initCmfiles() {
		Cm_Main.parseCmConfig();
		cmfileList = Cm_Main.getCmfileList();
	}

	public void generateXml() {
		FTPClientInterface client = new FTPClientImp();
		client.connect();
		for (int i = 0; i < cmfileList.size(); i++) {
			String xmlneName = cmfileList.get(i).getXmlnename();
			if (neName.trim().equals(xmlneName)) {
			} else {
				String name = generateXmlName(cmfileList.get(i).getCmheaders()
						.get(0).getCmfileheaders(), cmfileList.get(i)
						.getXmlnename());
				strBuf = new StringBuffer();
				writerFileHeader(cmfileList.get(i).getCmheaders().get(0)
						.getCmfileheaders());
				cmfileList.get(i).getCmrootobjs();
				writerRootObj(cmfileList.get(i).getCmrootobjs());
				writerObjs(cmfileList.get(i).getCmobjs());
				String str = strBuf.toString().replace("<DateTime></DateTime>", "123");
				openFileWriter(name,str);
				NrmUtil.CompressNrmFile(name);
				client.upLoadFile(name, "/home/yanbing/aaa.xml");
			}
			closeWriteBuf();
			ConnectionPool.releaseDbResource();
		}
		client.closeFtpClient();
	}

	public String generateXmlName(List<Cmfileheader> fileheaders, String type) {
		String name = null;
		for (int i = 0; i < fileheaders.size(); i++) {
			if (fileheaders.get(i).getHeadername().trim()
					.equals(Constant.fileNameAttr)) {
				name = fileheaders.get(i).getValue();
				break;
			}
		}
		if (name != null) {
			return "D:\\smallCell\\file\\" + type + "\\" + name + "-"
					+ NrmUtil.formatCurrentDate() + ".xml";
		} else {
			return name;
		}
	}

	public void writerFileHeader(List<Cmfileheader> fileheaders) {
		strBuf.append(Constant.startCmfileHeader);
		for (int i = 0; i < fileheaders.size(); i++) {
			strBuf.append("<" + fileheaders.get(i).getHeadername() + ">");
			strBuf.append(fileheaders.get(i).getValue());
			strBuf.append("</" + fileheaders.get(i).getHeadername() + ">"
					+ "\n");
		}
		strBuf.append(Constant.endCmfileHeader);
	}

	public void writerRootObj(List<Cm_root_object> rootObjs) {
		String obj_type = null;
		List<Root_sqlfield> rootSqlfields = rootObjs.get(0).getRootSqlfields();
		strBuf.append(Constant.startCmObjects);
		obj_type = rootObjs.get(0).getObj_root_type();
		strBuf.append(Constant.startobjType + obj_type + Constant.endobjType);
		strBuf.append(Constant.startCmfields);
		if (rootObjs.get(0).getSql_element().equals("")
				|| rootObjs.get(0) == null) {
			for (int i = 0; i < rootSqlfields.size(); i++) {
				strBuf.append("\t<N i=" + i + ">"
						+ rootSqlfields.get(i).getAttrname() + "</N>\n");
			}
			strBuf.append(Constant.endCmfields);
			strBuf.append(Constant.startCmfieldVal);
			for (int j = 0; j < rootSqlfields.size(); j++) {
				strBuf.append("\t<N i=" + j + ">"
						+ rootSqlfields.get(j).getDefaultRootVal() + "</N>\n");
			}
			strBuf.append(Constant.endCmfieldVal);
			strBuf.append(Constant.endCmObjects);
		} else {
		}

	}

	public void writerObjs(List<Cm_object> cmobjs) {
		try {
			strBuf.append(Constant.startCmObjects);
			for (int i = 0; i < cmobjs.size(); i++) {
				String obj_type = cmobjs.get(i).getObjType();
				strBuf.append(Constant.startobjType + obj_type
						+ Constant.endobjType);
				List<Sqlfield> sqlfields = cmobjs.get(i).getSqlfields();
				writeObjAttribues(sqlfields);
				String sql = cmobjs.get(i).getSqlelement();
				ResultSet rs = ConnectionPool.getSqlResult(sql);
				while (rs.next()) {
					writeObjValue(rs, sqlfields);
				}
			}
			strBuf.append(Constant.endCmObjects);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void writeObjAttribues(List<Sqlfield> sqlfields) {
		strBuf.append(Constant.startCmfields);
		for (int i = 0; i < sqlfields.size(); i++) {
			strBuf.append("\t<N i=" + i + ">" + sqlfields.get(i).getAttrname()
					+ "</N>\n");
		}
		strBuf.append(Constant.startCmfields);
	}

	public void writeObjValue(ResultSet rs, List<Sqlfield> sqlfields) {
		strBuf.append(Constant.startCmfieldVal);
		for (int i = 0; i < sqlfields.size(); i++) {
			writeValue(rs, sqlfields.get(i).getType(), sqlfields.get(i)
					.getAttrname(), i + 1);
		}
		strBuf.append(Constant.endCmfieldVal);
	}

	public void writeValue(ResultSet rs, String type, String name, int i) {
		try {
			if (type.equals("int")) {
				strBuf.append("\t<V i=" + i + ">" + rs.getInt(name) + "</V>\n");
			} else if (type.equals("date")) {
				strBuf.append("\t<V i=" + i + ">" + rs.getDate(name) + "</V>\n");
			} else {
				strBuf.append("\t<V i=" + i + ">" + rs.getString(name) + "</V>\n");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void openFileWriter(String fileName,String content) {
		if (fileName != null) {
			try {
				File nrmfile = new File(fileName);
				buf = new BufferedWriter(new FileWriter(nrmfile));
				buf.write(content);
				buf.flush();
			} catch (Exception e) {
				// throw(new Exception(e));
			}
		} else {
			System.exit(1);
		}
	}

	public void closeWriteBuf() {
		try {
			if (buf != null) {
				buf.flush();
				buf.close();
			}
		} catch (Exception e) {
			// throw(new Exception(e));
		}
	}

	public static void usage(){
		System.out.println();
		System.out.println("++++++++++++++++++++++++++Usage++++++++++++++++++++++++++++++");
		System.out.println("java GenerateCmFileImp -NeType '()' -Date '(20151220-180000)'");
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		System.out.println();
	}
	public static void main(String[] args) {
//		GenerateCmFileImp imp = new GenerateCmFileImp();
//		imp.initCmfiles();
//		imp.generateXml();
		if(args.length!=4){
			System.out.println("Command line Input Error.");
			usage();
		}

	}
}
